package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.commons.tool.utils.NumberUtils;
import com.mall.commons.tool.utils.TradeNoUtils;
import com.mall.order.biz.callback.SendEmailCallback;
import com.mall.order.biz.callback.TransCallback;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.order.utils.GlobalIdGeneratorUtil;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *  ciggar
 * create-date: 2019/8/1-下午5:01
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;


    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        Date currentDate = new Date();
        // TODO 发号器(全局id生成器)
        //String orderId = UUID.randomUUID().toString().replace("-", "");
        String orderId = TradeNoUtils.generateTradeNo();

        Order order = new Order();
        order.setOrderId(orderId);
        order.setPayment(createOrderContext.getOrderTotal());
        // 状态 0未付款 1已付款 2未发货 3已发货 4交易成功 5交易关闭 6交易失败 7-已退款
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        order.setCreateTime(currentDate);
        order.setUpdateTime(currentDate);
        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getBuyerNickName());
        // paymentType暂时不写
        // 支付类型，暂时不写 1在线支付 2货到付款
        // order.setPaymentType();
        // 邮费，发货时间，交易完成时间，交易关闭时间，物流名称，物流单号，买家留言，买家是否已评论，暂时不写
        // order.setPostFee();
        // order.setConsignTime();
        // order.setEndTime();
        // order.setCloseTime();
        // order.setShippingName();
        // order.setShippingCode();
        // order.setBuyerMessage();
        // order.setBuyerComment();

        // 数据库中插入订单信息
        int affectedRows = orderMapper.insert(order);
        if (affectedRows != 1) {
            throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
        }

        ArrayList<Long> buyProductIds = new ArrayList<>();
        // 数据库中插入订单商品关联信息
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            OrderItem orderItem = new OrderItem();
            // 注意：orderItem的id不是自增的
            // TODO 发号器(全局id生成器)
            //String orderItemId = UUID.randomUUID().toString().replace("-", "");
            String orderItemId = TradeNoUtils.generateTradeNo();
            orderItem.setId(orderItemId);
            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(orderId);
            orderItem.setNum(cartProductDto.getProductNum().intValue());
            orderItem.setTitle(cartProductDto.getProductName());
            orderItem.setPrice(cartProductDto.getSalePrice().doubleValue());
            Double totalFee = cartProductDto.getSalePrice().multiply(new BigDecimal(cartProductDto.getProductNum())).doubleValue();
            orderItem.setTotalFee(totalFee);
            orderItem.setPicPath(cartProductDto.getProductImg());
            // 1库存已锁定 2库存已释放 3-库存减扣成功
            orderItem.setStatus(1);

            buyProductIds.add(cartProductDto.getProductId());

            int affectedRow = orderItemMapper.insert(orderItem);
            if (affectedRow != 1) {
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
            }
        }
        // 插入订单后，需要设置createOrderContext的orderId，buyProductIds
        createOrderContext.setOrderId(orderId);
        createOrderContext.setBuyProductIds(buyProductIds);

        return true;
    }
}
